package com.tianyiyan.email;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.tianyiyan.tyenword.StaticData;


public class TyMail
{
   private static Properties properties = new Properties();
   private static String contentFormat;
   static
   {
	  properties.setProperty("mail.debug", StaticData.getInstance().getMailDebug());// Debug model
	  properties.setProperty("mail.transport.protocol", "smtp");//send protocol
	  properties.setProperty("mail.smtp.auth", "true");// Identity authentication
      properties.setProperty("mail.smtp.host", StaticData.getInstance().getSmtpHost());// 邮箱服务器
      properties.setProperty("mail.smtp.port", StaticData.getInstance().getSmtpPort());
//      properties.put("mail.smtp.socketFactory.port", "25");
//      properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
      contentFormat = "亲爱的%s，\n\n感谢您使用TyEnWord！请点击以下链接来验证您的电邮地址。\n%s\n如果点击以上链接无效，请将网站复制粘贴到新浏览器窗口打开。\n\n祝您玩得开心，\n您在TyEnWord的朋友";
   }
   
   public static boolean send(String email, String username, String token) 
   {
      try
      {
         Session session = Session.getDefaultInstance(properties,  
            new javax.mail.Authenticator() {
            protected PasswordAuthentication 
            getPasswordAuthentication() {
            return new 
            PasswordAuthentication(StaticData.getInstance().getEmail(), StaticData.getInstance().getEmailPasswd());
            }});

         Message message = new MimeMessage(session);
         message.setFrom(new InternetAddress(StaticData.getInstance().getEmail()));
         message.setRecipients(Message.RecipientType.TO, 
            InternetAddress.parse(email));
         message.setSubject("请验证您的电子邮件地址");
         message.setText(String.format(contentFormat, username, StaticData.getInstance().getServerHost() + "/emailVerification?code=" + token));
         Transport.send(message);
      }
      catch(Exception e)
      {
         e.printStackTrace();
         return false;
      }
      return true;
   }
}
